package com.scores.service.impl;

import com.scores.mapper.ScoreMapper;
import com.scores.mapper.StudentMapper;
import com.scores.mapper.SubjectMapper;
import com.scores.pojo.Score;
import com.scores.pojo.Student;
import com.scores.pojo.Subject;
import com.scores.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class SubjectServiceImpl implements SubjectService {

    @Autowired
    SubjectMapper subjectMapper;
    @Autowired
    ScoreMapper scoreMapper;


    @Override
    public List<Subject> getAllSubjectByPage(Subject subject, Integer page, Integer size) {
        if(subject.getSubjectName()!=null && !subject.getSubjectName().trim().isEmpty()) {
            subject.setSubjectName("%"+subject.getSubjectName().trim()+"%");
        }
        return subjectMapper.getAllSubjectByPage(subject, page, size);
    }

    @Override
    public int getAllSubjectCount(Subject subject) {
        if(subject.getSubjectName()!=null && !subject.getSubjectName().trim().isEmpty()) {
            subject.setSubjectName("%"+subject.getSubjectName().trim()+"%");
        }
        return subjectMapper.getAllSubjectCount(subject);
    }

    @Override
    public int addSubject(Subject subject) {
        List<Subject> subjectList = new ArrayList<>();
        subjectList.add(subject);
        int count = subjectMapper.addSubject(subjectList);
        if(count>0){
            return 0; // Success
        } else {
            return 2; // Failure
        }
    }

    @Override
    public int updateSubject(Subject subject) {
        int count = subjectMapper.updateSubject(subject);
        if(count>0){
            return 0; // Success
        } else {
            return 1; // Failure
        }
    }

    @Override
    public int deleteSubject(Subject subject) {
        List<Score> scoreList = scoreMapper.getScoreBySubjectId(subject.getSubjectId());
        if(scoreList != null && !scoreList.isEmpty()){
            return 2; // Cannot delete, scores exist
        }
        int count = subjectMapper.deleteSubjectByNo(subject);
        if(count > 0){
            return 0; // Number of deleted students
        } else {
            return 1; // Failure
        }
    }
}
